package com.basic.mq.handler;

import com.basic.dto.RankingListDTO;
import com.basic.mapper.RankingListMapper;
import com.basic.mq.MqMessageDTO;
import com.basic.mq.MqMessageHandler;
import com.basic.mq.MqMessageTypeEnum;
import com.basic.mq.dto.CommentMessageDTO;
import com.basic.mq.dto.RankingListMessageDTO;
import com.basic.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Component
public class RankingListMessageHandler implements MqMessageHandler {

    final static Logger logger = LoggerFactory.getLogger(RankingListMessageHandler.class);

    @Autowired
    private RankingListMapper rankingListMapper;

    @Override
    public void deal(MqMessageDTO messageDTO) {
        logger.info("处理排行榜的消息, message:{}", JsonUtils.objectToJson(messageDTO));
        String message = messageDTO.getMessage();

        if(StringUtils.isEmpty(message)) {
            logger.info("处理排行榜的消息, 消息为空");
            return;
        }

        RankingListMessageDTO rankingListMessageDTO;

        try {
            rankingListMessageDTO = JsonUtils.jsonToPojo(message, RankingListMessageDTO.class);
            if(rankingListMessageDTO == null) {
                logger.info("处理排行榜的消息, 消息转换为空, message:{}", message);
                return;
            }
        } catch (Exception e) {
            logger.info("处理排行榜的消息, 消息转换异常, message:{}, e:{}", message, JsonUtils.objectToJson(e));
            return;
        }

        RankingListDTO rankingListDTO = rankingListMapper.queryRankingListDTOByEssayId(rankingListMessageDTO.getEssayId());

        if(rankingListDTO == null) {
            logger.info("处理排行榜的消息, 排行榜不存在, message:{}", message);
            return;
        }

        long time = messageDTO.getCreateDate().getTime() - 60 * 60 *1000L;
        if(time > rankingListDTO.getScoreHourStartDate().getTime()) {
            List<RankingListDTO> rankingListDTOS = rankingListMapper.queryRankingListDTOList();

            //TODO 批量向redis中更换排行榜，使用Lua脚本操作

            rankingListDTO.setScoreHourStartDate(new Date());
        }
        rankingListDTO.setScoreHourLast(rankingListDTO.getScoreHourLast() + rankingListMessageDTO.getScore());
        rankingListDTO.setScoreTotal(rankingListDTO.getScoreTotal() + rankingListMessageDTO.getScore());
        rankingListDTO.setActiveValue(rankingListDTO.getScoreTotal() * 2 + rankingListDTO.getScoreHourLast() * 8);
        rankingListMapper.updateRankingListDTO(rankingListDTO);

    }

    @Override
    public Integer getMessageType() {
        return MqMessageTypeEnum.ASYNC_DEAL_RANKING_LIST.getCode();
    }
}
